package org.ezplatform.office.questionnaire.web.rest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.dingisv.util.OperationResultDing;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireAnswer;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopicOptions;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerService;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicOptionsService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicService;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/m/questionnaire")
public class QuestionnaireMobileApiController extends BaseController<Questionnaire, String>{
	
	private final static Logger LOG = LoggerFactory.getLogger(QuestionnaireMobileApiController.class);
	
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private QuestionnaireAnswerStatusService answerStatusService;
	
	@Autowired
	private RoleApiService roleApiService;
	
	@Autowired
	private QuestionnaireAnswerService answerService;
	
	@Autowired
	private PopUserScopeUtilService popUserUtilService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private QuestionnaireTopicService topicService;
	
	@Autowired
	private UserApiService userApiService;
	
	@Autowired
	private QuestionnaireTopicOptionsService optionService;
	
	@Autowired
	private SendMsgUtils sendMsgUtils;
	
	@Override
	protected BaseService<Questionnaire, String> getEntityService() {
        return questionnaireService;
    }
	
	/**
	 * 判断指定id的实体是否存在
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "实体类是否存在", notes = "")
	@RequestMapping(value="/entityIsExist", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public Map<String, Object> entityIsExist(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String id = request.getParameter("id");
			Questionnaire entity = this.questionnaireService.findOne(id);
			if (entity == null) {
				resultMap.put("content", "notExist");
			} else {
				resultMap.put("content", "exist");
			}
			resultMap.put("success", true);
		} catch (Exception e) {
			resultMap.put("success", false);
			resultMap.put("content", "");
		}
		return resultMap;
	}
	
	/**
     * 获取回退原因
     * @param request
     * @return
     */
    @RequestMapping(value="/getBackReason", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getBackReason(HttpServletRequest request) {
		String id = request.getParameter("id");
		Map<String, Object> result = new HashMap<>();
		QusetionnaireAnswerStatus qas = answerStatusService.findOne(id);
		result.put("type", "success");
		result.put("code", "0");
		result.put("message", qas.getBackReason());
		return OperationResultDing.buildSuccessResult(result);
	}
	
    /**
     * 获取问卷列表
     * @param request
     * @return
     */
    @RequestMapping(value="/getDingQuesList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getDingQuesList(HttpServletRequest request) {
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String quesType = request.getParameter("quesType");
		String quespublish = request.getParameter("quespublish");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(user.getUserId(), corpId, user.getJwtToken());
		boolean result = false;
		if (!roleList.isEmpty()) {
			String roleCode = "";
			for (Map<String, Object> map : roleList) {
				roleCode = StringUtils.null2String(map.get("roleCode"));
				if ("appAdminRole".equals(roleCode)) {
					result = true;
					break;
				}
			}
		}
		String userIdStr = user.getUserId();
		if (result) {
			userIdStr = "";
		}
		List<Map> mapList = questionnaireService.getQuesList(corpId, userIdStr, quesType, page, pageSize, search,
				quespublish, startDate, endDate);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", mapList);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}
    
    /**
     * 获取问卷列表
     * @param request
     * @return
     */
    @RequestMapping(value="/getDingMyQuesList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getDingMyQuesList(HttpServletRequest request) {
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String quesType = request.getParameter("quesType");
		String quespublish = request.getParameter("quespublish");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(user.getUserId(), corpId, user.getJwtToken());
		boolean result = false;
		if (!roleList.isEmpty()) {
			String roleCode = "";
			for (Map<String, Object> map : roleList) {
				roleCode = StringUtils.null2String(map.get("roleCode"));
				if ("appAdminRole".equals(roleCode)) {
					result = true;
					break;
				}
			}
		}
		String userIdStr = user.getUserId();
		if (result) {
			userIdStr = "";
		}
		List<Map> mapList = questionnaireService.getQuesList(corpId, userIdStr, quesType, page, pageSize, search,
				quespublish, startDate, endDate);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", mapList);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}
    
    
    /**
     * 获取我的答卷列表
     * @param request
     * @return
     */
    @RequestMapping(value="/getDingMyAnswerList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getDingMyAnswerList(HttpServletRequest request) {
		String quesType = request.getParameter("quesType");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String status = request.getParameter("status");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		List<Map> mapList = answerService.getAnswerList(quesType, corpId, user.getUserId(), token, page, pageSize,
				search, status, startDate, endDate);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (Map ques : mapList) {
			String queType = ques.get("type").toString();
			String createdDateStr = ques.get("createdDate").toString();
			Date createdDate = DateUtils.parseDate(createdDateStr, "yyyy-MM-dd HH:mm");
			String id = StringUtils.null2String(ques.get("id"));
			ques.put("createdDate", DateUtils.formatDate(createdDate));
			// 答卷的状态
			String answerStatus = StringUtils.null2String(ques.get("answerStatus"));
			if (StringUtils.equals(answerStatus, QusetionnaireAnswerStatus.StatusEnum.NOANSWER.getCode())
					|| StringUtils.isBlank(answerStatus)) {
				ques.put("answerStatus", "0");
				ques.put("status", "待答卷");
			} else if (StringUtils.equals(answerStatus, QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode())) {
				ques.put("status", "已提交");
			} else if (StringUtils.equals(answerStatus, QusetionnaireAnswerStatus.StatusEnum.DRAFT.getCode())) {
				ques.put("status", "草稿");
			} else if (StringUtils.equals(answerStatus, QusetionnaireAnswerStatus.StatusEnum.BACK.getCode())) {
				ques.put("status", "已回退");
			} else if (StringUtils.equals(answerStatus, "4")) {
				ques.put("status", "已提交");
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", mapList);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}
    
    /**
     * 获取成绩排名
     * @param request
     * @return
     */
    @RequestMapping(value="/getRankingList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getRankingList(HttpServletRequest request) {
		String quesId = request.getParameter("quesId");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		List<Map> mapList = answerStatusService.getDingRankingList(quesId, page, pageSize, corpId, token);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", mapList);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}
    
    /**
     * 获取问卷表单
     * @param request
     * @return
     */
    @RequestMapping(value="/getDingQuesForm", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getDingQuesForm(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> typeMap = new HashMap<String, Object>();
		typeMap.put("questionnaireVote", "投票");
		typeMap.put("questionnaireSurvey", "调查");
		map.put("types", list);
		return OperationResultDing.buildSuccessResult(map);
	}
    
    /**
     * 保存问卷
     * @param entity
     * @param model
     * @return
     * @throws ParseException 
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
	public OperationResultDing save(String entity, HttpServletRequest request) throws ParseException {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		String orgId = user.getOrgId();
		String userId = user.getUserId();
		Map<String, Object> data = JsonUtils.readValue(entity);
		String id = StringUtils.null2String(data.get("id"));
		String name = StringUtils.null2String(data.get("name"));
		boolean flag = questionnaireService.checkName(id, name, corpId);
		if (flag) {
			return OperationResultDing.buildFailureResult("该问卷名称已存在");
		}
    	boolean checkName = ((String) data.get("name")).contains("<script>");
    	if(checkName) {
    		return OperationResultDing.buildFailureResult("非法参数，禁止输入");
    	}
    	if(StringUtils.isNotEmpty((String)data.get("description"))) {
    		boolean checkDescription = ((String)data.get("description")).contains("<script>");
    		if(checkDescription) {
    			return OperationResultDing.buildFailureResult("非法参数，禁止输入");
    		}
    	}
		String quesType = data.get("quesType") == null ? "" : data.get("quesType").toString();
		String description = data.get("description") == null ? "" : data.get("description").toString();
		Questionnaire queEntity = null;
		String oldName = "";
		if (StringUtils.isNotBlank(id)) {
			queEntity = questionnaireService.findOne(id);
			oldName = queEntity.getName();
		} else {
			queEntity = new Questionnaire();
			queEntity.setCreatedBy(userId);
			queEntity.setCreatedOrg(orgId);
		}
		if (queEntity.getPublish() == Questionnaire.PublishEnum.DIES_VENIT.getCode()) {
			queEntity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
		}
		queEntity.setName(name);
		queEntity.setType(quesType);
		queEntity.setDescription(description);
		queEntity.setCloseDate(DateUtils.parseDate(data.get("closeDate")));
		/**
		 * 根据适用范围 获取总应答题人数
		 */
		String quesScopeList = data.get("quesScopeList").toString();
		if (quesScopeList == null || JSONArray.parseArray(quesScopeList).size() == 0) {
			List<Map> list = questionnaireService.getAllUser(corpId);
			queEntity.setAllUserNum(list.size());
		} else {
			Set<String> set = questionnaireService.getAllUserNum(quesScopeList, corpId, token);
			queEntity.setAllUserNum(set.size());
		}
		String quesScope = queEntity.getQuestionnaireScope();
		if (quesScopeList != null && JSONArray.parseArray(quesScopeList).size() > 0) {
			if ("".equals(StringUtils.null2String(quesScope))) {
				quesScope = UuidUtils.UUID();
				queEntity.setQuestionnaireScope(quesScope);
			}
			this.popUserUtilService.saveScopeData("oa_questionnaire_scope", quesScope, quesScopeList,
					"oa_questionnaire", "questionnaire_scope");
		} else {
			this.popUserUtilService.delScopeMethod("oa_questionnaire_scope", quesScope, "oa_questionnaire",
					"questionnaire_scope");
			queEntity.setQuestionnaireScope(null);
		}
		String answerScopeList = data.get("answerScopeList").toString();
		String answerScope = queEntity.getAnswerScope();
		if (answerScopeList != null && JSONArray.parseArray(answerScopeList).size() > 0) {
			if ("".equals(StringUtils.null2String(answerScope))) {
				answerScope = UuidUtils.UUID();
				queEntity.setAnswerScope(answerScope);
			}
			this.popUserUtilService.saveScopeData("oa_questionnaire_scope", answerScope, answerScopeList,
					"oa_questionnaire", "answer_scope");
		} else {
			this.popUserUtilService.delScopeMethod("oa_questionnaire_scope", answerScope, "oa_questionnaire",
					"answer_scope");
			queEntity.setAnswerScope(null);
		}
		queEntity.setCorpId(corpId);
		if (StringUtils.isBlank(id)) {
			queEntity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
		}
		questionnaireService.save(queEntity);
		if (StringUtils.isNotBlank(id)) {
			// 日志启用标记
			boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:02", user.getJwtToken());
			if (optLogFlag) {
				// 记录日志
				this.logService.saveModuleLog("questionnaireLog:manage:02", oldName, "");
			}
		}
		return OperationResultDing.buildSuccessResult("保存成功");
	}
	
    /**
     * 获取问卷详情
     * @param request
     * @return
     */
    @RequestMapping(value="/getDingQuesInfo", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public OperationResultDing getDingQuesInfo(HttpServletRequest request) {
		String id = request.getParameter("id");
		String isAnwser = request.getParameter("isAnwser");
		String anUserId = request.getParameter("anUserId");
		WebUser user = WebUtils.getCurrentUser();
		String userId = "";
		if (StringUtils.isNotBlank(anUserId)) {
			userId = anUserId;
		} else {
			userId = user.getUserId();
		}
		Map<String, Object> map = new HashMap<>();
		Questionnaire oq = questionnaireService.findOne(id);
		if (oq == null) {
			map.put("isDeleted", true);
			return OperationResultDing.buildSuccessResult(map);
		} else {
			map.put("isDeleted", false);
		}
		List<QuestionnaireTopic> list = topicService.getDingTopicOPtionInfo(id, userId, isAnwser, user.getJwtToken());
		map.put("topicSetting", list);
		String titleSetting = StringUtils.null2String(oq.getTitleSetting());
		if (!"".equals(titleSetting)) {
			Map<String, Object> mapSetting = new HashMap<String, Object>();
			mapSetting = JsonUtils.readValue(titleSetting);
			map.put("titleSetting", mapSetting);
		} else {
			map.put("titleSetting", titleSetting);
		}
		map.put("entity", oq);
		// 获取用户答卷状态
		QusetionnaireAnswerStatus answerStatus = this.answerStatusService.findAnswerStatus(userId, id);
		String anStatus = "0";
		if (answerStatus != null) {
			anStatus = answerStatus.getStatus();
			map.put("grade", answerStatus.getGrade());
			map.put("ranking", answerStatus.getRanking());
			map.put("answerNum", answerStatus.getAnswerNum());
		}
		map.put("answerStatus", anStatus);
		map.put("answerCount", answerStatusService.getAnswerNumByQuesId(id));// 答卷人数
		return OperationResultDing.buildSuccessResult(map);
	}
    
    /**
     * 保存答卷
     * @param entity
     * @return
     * @throws ParseException 
     */
    @RequestMapping(value = "/answerEdit", method = RequestMethod.POST)
    @ResponseBody
	public OperationResultDing answerEdit(String entity, HttpServletRequest request) throws ParseException {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		String orgId = user.getOrgId();
		String userId = user.getUserId();
		String quesId = request.getParameter("quesId");
		String submitType = request.getParameter("type");
		String quesType = request.getParameter("quesType");
		String grade = request.getParameter("grade");
		String timingFlag = request.getParameter("timingFlag");
		List<Map<String, Object>> data = JsonUtils.readListValue(entity);
		String orgIds = "";
		List<Map<String, Object>> userMapList = userApiService.getUserRelatedInfo(userId, "1", corpId, token);
		if (CollectionUtils.isNotEmpty(userMapList)) {
			for (Map<String, Object> map : userMapList) {
				orgIds = StringUtils.null2String(map.get("orgId"));
			}
		}
		if (data.size() == 0) {
			return OperationResultDing.buildFailureResult("参数不能为空");
		}
		/*QusetionnaireAnswerStatus aStatus = answerStatusService.findAnswerStatus(userId, quesId);
		if (aStatus != null && "1".equals(aStatus.getStatus())) {
			return OperationResultDing.buildFailureResult("该问卷已提交");
		}*/
		List<QuestionnaireAnswer> list = new ArrayList<QuestionnaireAnswer>();
		for (int i = 0; i < data.size(); i++) {
			Map<String, Object> item = data.get(i);
			String type = item.get("topicType").toString();
			if ("illustrate".equals(type)) {// 说明直接跳过
				continue;
			}
			if ("sinselect".equals(type) || "trueOrFalse".equals(type)) { // 单选
				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				oaAnswer.setAnswer(item.get("answer").toString());
				oaAnswer.setTopicId(item.get("id").toString());
				oaAnswer.setQuestionnaireId(quesId);
				oaAnswer.setOptionId(item.get("answer").toString());
				oaAnswer.setUserId(userId);
				oaAnswer.setCreatedBy(userId);
				oaAnswer.setCreatedOrg(orgId);
				oaAnswer.setAnswerExt(item.get("answerExt").toString());
				String franction = item.get("fraction").toString();
				if (!"".equals(StringUtils.null2String(franction))) {
					oaAnswer.setFraction(Float.parseFloat(franction));
				}
				list.add(oaAnswer);
			} else if ("multiselect".equals(type)) { // 多选
				String answer = item.get("answer").toString();
				String franction = item.get("fraction").toString();
				if (!"".equals(StringUtils.null2String(answer))) {
					String[] answerArray = answer.split(",");
					for (int j = 0; j < answerArray.length; j++) {
						QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
						oaAnswer.setAnswer(answerArray[j]);
						oaAnswer.setTopicId(item.get("id").toString());
						oaAnswer.setQuestionnaireId(quesId);
						oaAnswer.setOptionId(answerArray[j]);
						oaAnswer.setUserId(userId);
						oaAnswer.setCreatedBy(userId);
						oaAnswer.setCreatedOrg(orgId);
						String optionlist = item.get("list").toString();
						JSONArray optionObj = JSONArray.parseArray(optionlist);
						if (!optionObj.isEmpty()) {
							int num = 0;
							for (int k = 0; k < optionObj.size(); k++) {
								JSONObject obj = JSONObject.parseObject(optionObj.get(k).toString());
								if ("true".equals(obj.getString("checked"))) {
									if (num == j) {
										oaAnswer.setAnswerExt(obj.getString("answerExt"));
									}
									num += 1;
								}
							}
						}
						String franctionItem = franction;
						if (!"".equals(StringUtils.null2String(franctionItem))) {
							oaAnswer.setFraction(Float.parseFloat(franctionItem));
						}
						list.add(oaAnswer);
					}
				}
			} else if ("check".equals(type)) { // 下拉
				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				oaAnswer.setAnswer(item.get("answer").toString());
				oaAnswer.setTopicId(item.get("id").toString());
				oaAnswer.setQuestionnaireId(quesId);
				oaAnswer.setOptionId(item.get("answer").toString());
				oaAnswer.setUserId(userId);
				oaAnswer.setCreatedBy(userId);
				oaAnswer.setCreatedOrg(orgId);
				oaAnswer.setAnswerExt(item.get("answerExt").toString());
				list.add(oaAnswer);
			} else if ("fillInBlanks".equals(type)) { // 填空
				List<Map<String, Object>> answer = (List<Map<String, Object>>) item.get("answer");
				if (answer.size() > 0) {
					for (int j = 0; j < answer.size(); j++) {
						String answerValue = answer.get(j).get("value").toString();
						QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
						oaAnswer.setAnswer(answerValue);
						oaAnswer.setTopicId(item.get("id").toString());
						oaAnswer.setQuestionnaireId(quesId);
						oaAnswer.setOptionId(answer.get(j).get("id").toString());
						oaAnswer.setUserId(userId);
						oaAnswer.setCreatedBy(userId);
						oaAnswer.setCreatedOrg(orgId);
						oaAnswer.setAnswerExt("");
						String franctionItem = answer.get(j).get("fraction").toString();
						if (!"".equals(StringUtils.null2String(franctionItem))) {
							oaAnswer.setFraction(Float.parseFloat(franctionItem));
						}
						list.add(oaAnswer);
					}
				}
			} else if ("answer".equals(type) || "shortAnswer".equals(type)) { // 问答
				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				oaAnswer.setAnswer(item.get("answer").toString());
				oaAnswer.setTopicId(item.get("id").toString());
				oaAnswer.setQuestionnaireId(quesId);
				oaAnswer.setOptionId(item.get("optionId").toString());
				oaAnswer.setUserId(userId);
				oaAnswer.setCreatedBy(userId);
				oaAnswer.setCreatedOrg(orgId);
				oaAnswer.setAnswerExt(item.get("answerExt").toString());
				String franction = item.get("fraction").toString();
				if (!"".equals(StringUtils.null2String(franction))) {
					oaAnswer.setFraction(Float.parseFloat(franction));
				}
				list.add(oaAnswer);
			} else if ("field".equals(type)) { // 附件
				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				oaAnswer.setAnswer(item.get("answerIds").toString());
				oaAnswer.setTopicId((String) item.get("topicId"));
				oaAnswer.setQuestionnaireId(quesId);
				if (StringUtils.isEmpty((String) item.get("optionId"))) {
					String uuid = UuidUtils.UUID();
					oaAnswer.setOptionId(uuid);
				} else {
					oaAnswer.setOptionId((String) item.get("optionId"));
				}
				oaAnswer.setCreatedBy(userId);
				oaAnswer.setCreatedOrg(orgId);
				oaAnswer.setUserId(userId);
				list.add(oaAnswer);
			} else if ("scale".equals(type)) { // 矩阵
				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				oaAnswer.setAnswer(item.get("answer").toString());
				oaAnswer.setTopicId(item.get("id").toString());
				oaAnswer.setQuestionnaireId(quesId);
				oaAnswer.setOptionId(item.get("answer").toString());
				oaAnswer.setUserId(userId);
				oaAnswer.setCreatedBy(userId);
				oaAnswer.setCreatedOrg(orgId);
				oaAnswer.setAnswerExt(item.get("answerExt").toString());
				list.add(oaAnswer);
			} else if ("mulscale".equals(type)) { // 矩阵量表
				List<Map<String, Object>> answer = (List<Map<String, Object>>) item.get("answer");
				if (answer.size() > 0) {
					for (int j = 0; j < answer.size(); j++) {
						if (!"".equals(answer.get(j).get("value").toString()) && answer.get(j).get("value") != null) {
							String answerValue = answer.get(j).get("value").toString();
							if (!"".equals(answerValue)) {
								QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
								oaAnswer.setAnswer(answerValue);
								oaAnswer.setTopicId(item.get("id").toString());
								oaAnswer.setQuestionnaireId(quesId);
								oaAnswer.setOptionId(answer.get(j).get("id").toString());
								oaAnswer.setUserId(userId);
								oaAnswer.setCreatedBy(userId);
								oaAnswer.setCreatedOrg(orgId);
								oaAnswer.setAnswerExt("");
								list.add(oaAnswer);
							}
						}
					}
				}
			}
		}
		answerService.deleteAnswerByQuesId(userId, quesId);
		answerService.save(list);
		// 答卷状态 1是提交，2是草稿，4评卷
		String anStatus = submitType;
		// 自动保存不更新答卷状态
		if (!"1".equals(timingFlag)) {
			QusetionnaireAnswerStatus answerStatus = answerStatusService.findAnswerStatus(userId, quesId);
			Date date = new Date();
			if (answerStatus == null) {
				QusetionnaireAnswerStatus newAnswerStatus = new QusetionnaireAnswerStatus();
				newAnswerStatus.setQuestionnaireId(quesId);
				newAnswerStatus.setOrgId(orgIds);
				newAnswerStatus.setStatus(anStatus);
				newAnswerStatus.setCreatedBy(userId);
				newAnswerStatus.setCreatedOrg(orgId);
				newAnswerStatus.setAnswerNum(1);
				if (StringUtils.isNotEmpty(grade))
					newAnswerStatus.setGrade(Float.parseFloat(grade));
				answerStatusService.save(newAnswerStatus);
			} else {
				answerStatus.setStatus(anStatus);
				answerStatus.setOrgId(orgIds);
				answerStatus.setCreatedDate(date);
				answerStatus.setCreatedBy(userId);
				answerStatus.setCreatedOrg(orgId);
				answerStatus.setAnswerNum(answerStatus.getAnswerNum()+1);
				if (StringUtils.isNotEmpty(grade))
					answerStatus.setGrade(Float.parseFloat(grade));
				answerStatusService.save(answerStatus);
			}
		}
		if ("questionnaireExam".equals(quesType) && "1".equals(anStatus))
			answerStatusService.rankingByGrade(quesId);// 无主观题直接进行排名
		if ("1".equals(anStatus) || "4".equals(anStatus)) {
			RestClient restClient = new RestClient(true);
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("receiver", "[{\"10\":\"" + userId + "\"}]");
			paramMap.put("corpId", corpId);
			paramMap.put("moduleCode", "questionnaire");
			paramMap.put("dataId", quesId);
			paramMap.put("msgType", "1");
			String jsonStr = restClient.post("/system/umc/message/takeMsgDone", token, paramMap);
//			Map<String, Object> result = JsonUtils.readValue(jsonStr);
//			if (MapUtils.isNotEmpty(result)) {
//				if ("failure".equals(result.get("type"))) {
//					LOG.error(String.valueOf(result.get("message")));
//					QusetionnaireAnswerStatus answerStatus = answerStatusService.findAnswerStatus(userId,quesId);
//	    	    	  answerStatus.setStatus("0");
//	    	    	  answerStatusService.save(answerStatus);
//					return OperationResultDing.buildFailureResult("还未收到消息提醒，收到提醒后方可答卷");
//				}
//			}
		}
		return OperationResultDing.buildSuccessResult("保存成功");
	}

    /**
     * 更新问卷发布状态
     * @param request
     * @return
     */
	@GetMapping("/updateQuesPublish")
    public OperationResultDing updateQuesPublish(HttpServletRequest request){
		//问卷id
		String quesId = request.getParameter("quesId");
		quesId = StringUtils.isNotBlank(quesId)?quesId:"";
		//问卷状态
		String publish = request.getParameter("publish");
		publish = StringUtils.isNotBlank(publish)?publish:"";
		WebUser user = WebUtils.getCurrentUser();
		Map<String, Object> result = new HashMap<>();
		//发布
		if(StringUtils.equals(publish,StringUtils.null2String(Questionnaire.PublishEnum.NOPUBLISH.getCode()))){
			int i = questionnaireService.updateQuesPublish(quesId,Questionnaire.PublishEnum.PUBLISH.getCode());
			if(i > 0){
				final String quesIdConst=quesId;
				new Thread(new Runnable() {
					@Override
					public void run() {
						questionnaireService.sendThreadQues(quesIdConst,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
						
					}},"sendQuestionnaireThread").start();
				
			}
			result.put("type", "success");
			result.put("code", "0");
			result.put("message", "发布成功");
			return OperationResultDing.buildSuccessResult(result);
		}
		//取消发布
		if(StringUtils.equals(publish,StringUtils.null2String(Questionnaire.PublishEnum.PUBLISH.getCode()))){
			result.put("type", "success");
			result.put("code", "0");
			int i = questionnaireService.updateQuesPublish(quesId,Questionnaire.PublishEnum.NOPUBLISH.getCode());
			if(i > 0){
				result.put("message", "操作成功");
				return OperationResultDing.buildSuccessResult(result);
			}
			result.put("message", "取消出错了");
			return OperationResultDing.buildSuccessResult(result);
		}
		result.put("type", "failure");
		result.put("code", "-1");
		result.put("message", "参数报错了");
		return OperationResultDing.buildSuccessResult(result);
	}

	/**
	 * 删除指定id的问卷
	 * @param request
	 * @return
	 */
	@GetMapping("/deletQuesById")
	public OperationResultDing deletQuesById(HttpServletRequest request) {
		// 问卷id
		String quesId = request.getParameter("quesId");
		quesId = StringUtils.isNotBlank(quesId) ? quesId : "";
		WebUser user = WebUtils.getCurrentUser();
		Map<String, Object> result = new HashMap<>();
		try {
			Questionnaire questionnaire = questionnaireService.findOne(quesId);
			if (questionnaire == null) {
				result.put("type", "failure");
				result.put("code", "-1");
				result.put("message", "该问卷不存在");
				return OperationResultDing.buildSuccessResult(result);
			}
			if (questionnaire.getPublish() == Questionnaire.PublishEnum.PUBLISH.getCode()) {
				result.put("type", "failure");
				result.put("code", "-1");
				result.put("message", "该问卷已发布，不能删除");
				return OperationResultDing.buildSuccessResult(result);
			}
			// 日志启用标记
			boolean optLogFlag = this.logService.checkOptLog(user.getCorpId(), "questionnaireLog:manage:04", user.getJwtToken());
			if (optLogFlag) {
				// 记录日志
				this.logService.saveModuleLog("questionnaireLog:manage:04", questionnaire.getName(), "");
			}
			// 查询问卷题目
			List<String> topicList = topicService.getTopicIdByQeusId(quesId);
			// 删除答卷
			if (CollectionUtils.isNotEmpty(topicList)) {
				answerStatusService.deleteStatusByQuesId(quesId);
				answerService.deleteAnswerByQuesId(quesId);
				// 删除问卷选项
				optionService.deleteOptionsByTopicId(topicList);
				topicService.deleteTopicByQuesId(quesId);
			}
			// 删除适用范围
			List<String> quesIds = new ArrayList<>();
			quesIds.add(quesId);
			List<String> quesScopeList = questionnaireService.getQuesScopeById(quesIds);
			List<String> answerScopeList = questionnaireService.getAnswerScopeById(quesIds);
			popUserUtilService.delScopeMethod("oa_questionnaire_scope", quesScopeList, "oa_questionnaire",
					"questionnaire_scope");
			popUserUtilService.delScopeMethod("oa_questionnaire_scope", answerScopeList, "oa_questionnaire",
					"answer_scope");
			questionnaireService.delete(questionnaire);
			sendMsgUtils.deleteMessage(Arrays.asList(quesId), user.getCorpId(), user.getJwtToken());
			result.put("type", "success");
			result.put("code", "0");
			result.put("message", "删除成功");
			return OperationResultDing.buildSuccessResult(result);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("type", "failure");
			result.put("code", "-1");
			result.put("message", "删除失败");
			return OperationResultDing.buildSuccessResult(result);
		}
	}

	/**
	 * 根据id查询问卷信息
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getQuesInfoById")
	public OperationResultDing getQuesInfoById(HttpServletRequest request) {
		String quesId = request.getParameter("quesId");
		quesId = StringUtils.isNotBlank(quesId) ? quesId : "";
		WebUser user = WebUtils.getCurrentUser();
		Map<String, Object> result = new HashMap<>();
		try {
			Map<String, Object> questionnaire = questionnaireService.getQuesById(quesId);
			if (MapUtils.isNotEmpty(questionnaire)) {
				if ("view".equals(request.getParameter("type"))) {
					// 日志启用标记
					boolean optLogFlag = this.logService.checkOptLog(user.getCorpId(), "questionnaireLog:manage:03",
							user.getJwtToken());
					if (optLogFlag) {
						// 记录日志
						this.logService.saveModuleLog("questionnaireLog:manage:03", (String) questionnaire.get("name"),
								"");
					}
				}
				/*
				 * 获取问卷题目的集合
				 */
				List<QuestionnaireTopic> questionnaireTopicList = topicService.getTopicOPtionInfo(quesId,
						user.getUserId(), user.getJwtToken(),true);
				/*
				 * 当问卷设计过题目后，就不能在编辑问卷类型
				 */
				if (questionnaireTopicList == null || questionnaireTopicList.size() == 0) {
					questionnaire.put("typeAble", "0"); // false
				} else {
					questionnaire.put("typeAble", "1"); // true
				}
				result.put("type", "success");
				result.put("code", "0");
				result.put("message", "处理成功");
				result.put("data", questionnaire);
				return OperationResultDing.buildSuccessResult(result);
			} else {
				result.put("type", "failure");
				result.put("code", "-1");
				result.put("message", "问卷不存在");
				return OperationResultDing.buildSuccessResult(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("type", "failure");
			result.put("code", "-1");
			result.put("message", "查询出错");
			return OperationResultDing.buildSuccessResult(result);
		}
	}

	/**
	 * 保存设计问卷
	 * 
	 * @param entity
	 * @param request
	 * @return
	 */
	@PostMapping("/saveDesign")
	public OperationResultDing saveDesign(String entity, HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String orgId = user.getOrgId();
		String userId = user.getUserId();
		String quesId = request.getParameter("quesId");
		Map<String, Object> data = JsonUtils.readValue(entity);
		// 保存题目选项
		List<QuestionnaireTopic> listTopic = new ArrayList<QuestionnaireTopic>();
		List<QuestionnaireTopicOptions> listOptions = new ArrayList<QuestionnaireTopicOptions>();
		String quesitionnaireId = quesId;
		List list = (List) data.get("list");// 单选
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> topicMap = (Map<String, Object>) list.get(i);
				int topicOrderNo = i + 1;
				List optionSetting = (List) topicMap.get("options");
				topicMap.put("sortNo", topicOrderNo);
				QuestionnaireTopic topic = new QuestionnaireTopic();
				topic = topicService.getDingSaveTopicInfo(topicMap, quesitionnaireId,
						(String) topicMap.get("quesType"));
				topic.setCreatedBy(userId);
				topic.setCreatedOrg(orgId);
				topic.setCreatedDate(new Date());
				listTopic.add(topic);
				List<QuestionnaireTopicOptions> listOption = optionService.getDingSaveOptionsInfo(optionSetting,
						topic.getId(), userId, orgId);
				listOptions.addAll(listOption);
			}
		}
		List<String> topicList = topicService.getTopicIdByQeusId(quesitionnaireId);
		if (topicList != null && topicList.size() > 0) {
			optionService.deleteOptionsByTopicId(topicList);
			topicService.deleteTopicByQuesId(quesitionnaireId);
		}
		topicService.save(listTopic);
		optionService.save(listOptions);
		questionnaireService.updateQuesMobile(quesId, entity, "1");
		return OperationResultDing.buildSuccessResult("保存成功");
	}
	
	/**
	 * 手机发送提醒
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping("/telSendMessage")
	public OperationResultDing telSendMessage(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		String userId = request.getParameter("userId");
		String quesId = request.getParameter("quesId");
		String isBatchSelect = request.getParameter("isBatchSelect");
		if ("true".equals(isBatchSelect)) {
			List<String> list = answerService.getStatisticsNoAnswerInfo(quesId, "", "", token);
			userId = StringUtils.join(list, ",");
		}
		// 回退问卷推送
		Map<String, Object> map = new HashMap<>();
		Questionnaire questionnaire = questionnaireService.findOne(quesId);
		// 问卷名称
		map.put("quesName", questionnaire.getName());
		// 问卷结束时间
		map.put("closeDate", questionnaire.getCloseDate());
		map.put("quesId", quesId);
		map.put("userIds", userId);
		map.put("type", SendMsgUtils.OVER_DUE);
		map.put("remindTarget", questionnaire.getRemindTarget());
		sendMsgUtils.sendMsgToApp(corpId, token, map, request, user.getUserId());
		String joinIds = "[{\"10\":\"" + userId + "\"}]";
		Map<String, String> paramMap = new HashMap<>();
		paramMap.put("userId", user.getUserId());
		paramMap.put("corpId", corpId);
		paramMap.put("token", token);
		paramMap.put("msgTitle", "您有一份问卷截止日期快到了，请及时答卷");
		paramMap.put("dataId", UuidUtils.UUID());
		paramMap.put("msgContent", "您有一份问卷截止日期快到了，请及时答卷");
		paramMap.put("url", SendMsgUtils.QUES_ANSWER_URL);
		paramMap.put("quesitionnaireId", quesId);
		paramMap.put("msgReceiver", joinIds);
		sendMsgUtils.sendMsgToOffice(paramMap);
		return OperationResultDing.buildSuccessResult("提醒成功");
	}

	/**
	 * 获取问卷题目
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getQuestTopic")
	public OperationResultDing getQuestTopic(HttpServletRequest request) {
		String quesId = request.getParameter("quesId");
		Questionnaire questionnaire = questionnaireService.findOne(quesId);
		Map<String, Object> result = new HashMap<>();
		result.put("type", "success");
		result.put("code", "0");
		result.put("message", "处理成功");
		result.put("data", questionnaire);
		return OperationResultDing.buildSuccessResult(result);
	}

	/**
	 * 获取登录用户姓名
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getUserName")
	public OperationResultDing getUserName(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		return OperationResultDing.buildSuccessResult(user.getCnName());
	}

	/**
	 * 获取统计列表
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getStatisticsList")
	public OperationResultDing getStatisticsList(HttpServletRequest request) {
		String quesType = request.getParameter("quesType");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String status = request.getParameter("status");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		WebUser user = WebUtils.getCurrentUser();
		List<Map> list = questionnaireService.getStaticList2Mobile(startDate, endDate, quesType, status, search, page,
				pageSize, user.getUserId(), user.getCorpId(), user.getJwtToken());
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", list);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}

	/**
	 * 获取提交人员列表
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getStatisticsPersonList")
	public OperationResultDing getStatisticsPersonList(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String roles = user.getRoleCodes();
		String isAdmin = "";
		if (roles.contains("appAdminRole")) {
			isAdmin = "1";
		} else {
			isAdmin = "0";
		}
		String quesId = request.getParameter("quesId");// 问卷id
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String orgId = request.getParameter("orgId");
		List<Map> list = answerService.getStatisticsAnswerList2Mobile(quesId, user.getCorpId(), user.getUserId(),
				search, orgId, page, pageSize, isAdmin, user.getJwtToken());
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", list);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}
	
	/**
	 * 获取未答人员列表
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getNoAnwserPersonList")
	public OperationResultDing getNoAnwserPersonList(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String quesId = request.getParameter("quesId");// 问卷id
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String search = request.getParameter("search");
		String orgId = request.getParameter("orgId");
		List<Map> list = answerService.getStatisticsNoAnswerInfoMB(quesId, user.getCorpId(), search, page, pageSize,
				user.getJwtToken(), search, orgId);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", list);
		resultMap.put("currentPage", Integer.parseInt(page));
		return OperationResultDing.buildSuccessResult(resultMap);
	}

	/**
	 * 回退问卷
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/quesBack")
	public OperationResultDing quesBack(HttpServletRequest request) {
		String id = request.getParameter("id");
		String backReason = request.getParameter("backReason");
		WebUser user = WebUtils.getCurrentUser();
		Map<String, Object> result = new HashMap<>();
		QusetionnaireAnswerStatus qusetionnaireAnswerStatus = answerStatusService.findOne(id);
		if (qusetionnaireAnswerStatus != null) {
			if ("2".equals(qusetionnaireAnswerStatus.getStatus())
					|| "3".equals(qusetionnaireAnswerStatus.getStatus())) {
				result.put("type", "success");
				result.put("code", "0");
				result.put("message", "回退成功");
				return OperationResultDing.buildSuccessResult(result);
			} else {
				answerStatusService.replyQusetionnaireByIds(backReason, Arrays.asList(id));
				// 回退问卷推送
				Map<String, Object> map = new HashMap<>();
				Questionnaire questionnaire = questionnaireService
						.findOne(qusetionnaireAnswerStatus.getQuestionnaireId());
				// 问卷名称
				map.put("quesName", questionnaire.getName());
				// 问卷结束时间
				map.put("closeDate", questionnaire.getCloseDate());
				map.put("quesId", qusetionnaireAnswerStatus.getQuestionnaireId());
				map.put("userIds", qusetionnaireAnswerStatus.getCreatedBy());
				map.put("type", SendMsgUtils.REPLYSTATUS);
				map.put("backReason", backReason);
				sendMsgUtils.sendMsgToApp(user.getCorpId(), user.getJwtToken(), map, request, user.getUserId());
				String joinIds = "[{\"10\":\"" + qusetionnaireAnswerStatus.getCreatedBy() + "\"}]";
				Map<String, String> paramMap = new HashMap<>();
				paramMap.put("userId", user.getUserId());
				paramMap.put("corpId", user.getCorpId());
				paramMap.put("token", user.getJwtToken());
				paramMap.put("msgTitle", SendMsgUtils.REPLY_FOR_HOA + questionnaire.getName());
				paramMap.put("dataId", UuidUtils.UUID());
				paramMap.put("msgContent", SendMsgUtils.REPLY_FOR_HOA + questionnaire.getName());
				paramMap.put("url", SendMsgUtils.QUES_ANSWER_URL);
				paramMap.put("quesitionnaireId", questionnaire.getId());
				paramMap.put("msgReceiver", joinIds);
				sendMsgUtils.sendMsgToOffice(paramMap);
				result.put("type", "success");
				result.put("code", "0");
				result.put("message", "回退成功");
				return OperationResultDing.buildSuccessResult(result);
			}
		}
		result.put("type", "failure");
		result.put("code", "-1");
		result.put("message", "问卷不存在");
		return OperationResultDing.buildSuccessResult(result);
	}

	/**
	 * 问卷统计
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getStatistics")
	public OperationResultDing getStatistics(HttpServletRequest request) {
		String quesId = request.getParameter("quesId");
		WebUser user = WebUtils.getCurrentUser();
		// 答卷数
		int num = answerStatusService.getAnswerNum(quesId, "1");
		// 答卷总人数
		int allUser = topicService.getQuestAnswerNum(quesId, user.getJwtToken(), user.getCorpId());
		Map<String, Object> map = new HashMap<>();
		Questionnaire oq = questionnaireService.findOne(quesId);
		List<QuestionnaireTopic> list = topicService.getStatistics(quesId, num, allUser, oq.getType());
		if (!CollectionUtils.isEmpty(list)) {
			for (QuestionnaireTopic questionnaireTopic : list) {
				if (StringUtils.isNotEmpty(questionnaireTopic.getRuleTopicName())) {
					questionnaireTopic.setRuleTopicName(questionnaireTopic.getRuleTopicName().replace("<br/>", "\n"));
					questionnaireTopic.setRuleTopicName(questionnaireTopic.getRuleTopicName().replace("&nbsp;", " "));
				}
			}
		}
		map.put("topicSetting", list);
		String titleSetting = StringUtils.null2String(oq.getTitleSetting());
		if (!"".equals(titleSetting)) {
			Map<String, Object> mapSetting = new HashMap<String, Object>();
			mapSetting = JsonUtils.readValue(titleSetting);
			map.put("titleSetting", mapSetting);
		} else {
			map.put("titleSetting", titleSetting);
		}
		map.put("entity", oq);
		map.put("topicAnswerNum", num);
		Map<String, Object> result = new HashMap<>();
		result.put("type", "success");
		result.put("code", "0");
		result.put("message", "处理成功");
		result.put("data", map);
		return OperationResultDing.buildSuccessResult(result);
	}

	/**
	 * 特殊题型详情数据查询
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getOptionDetail")
	public OperationResultDing getOptionDetail(HttpServletRequest request) {
		// 题目id
		String topicId = request.getParameter("topicId");
		// 问卷id
		String quesId = request.getParameter("quesId");
		// 题型
		String topicType = request.getParameter("topicType");
		WebUser user = WebUtils.getCurrentUser();
		List<Map> list = answerService.getAnswerDetail(quesId, topicType, topicId, user.getJwtToken(),
				user.getCorpId());
		Map<String, Object> result = new HashMap<>();
		result.put("type", "success");
		result.put("code", "0");
		result.put("message", "处理成功");
		result.put("data", list);
		return OperationResultDing.buildSuccessResult(result);
	}

}
